// DOM 元素
const loginBtn = document.getElementById('loginBtn');
const loginModal = document.getElementById('loginModal');
const closeBtn = document.querySelector('.close-btn');
const tabBtns = document.querySelectorAll('.tab-btn');
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const videoGrid = document.querySelector('.video-grid');
const navLinks = document.querySelector('.nav-links');
const captchaImage = document.getElementById('captchaImage');

// Token管理
let token = localStorage.getItem('token');

// 模拟视频数据
const mockVideos = [
    {
        id: 1,
        title: '未来科技展示',
        thumbnail: 'https://picsum.photos/300/200',
        views: '1.2k'
    },
    {
        id: 2,
        title: 'AI技术突破',
        thumbnail: 'https://picsum.photos/300/201',
        views: '2.5k'
    },
    {
        id: 3,
        title: '量子计算进展',
        thumbnail: 'https://picsum.photos/300/202',
        views: '3.8k'
    }
];

// 头像预览功能
const avatarInput = document.getElementById('avatar');
const avatarPreview = document.getElementById('avatarPreview');

avatarInput.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            avatarPreview.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
});

// 检查登录状态
async function checkLoginStatus() {
    if (!token) {
        updateUIForLoggedOut();
        return;
    }

    try {
        const response = await fetch('/api/auth/user', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        if (response.ok) {
            const user = await response.json();
            updateUIForLoggedIn(user);
        } else {
            localStorage.removeItem('token');
            updateUIForLoggedOut();
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        localStorage.removeItem('token');
        updateUIForLoggedOut();
    }
}

// 更新UI为已登录状态
function updateUIForLoggedIn(user) {
    loginBtn.textContent = user.nickname;
    loginBtn.href = '#';
    
    // 添加退出按钮
    const logoutBtn = document.createElement('a');
    logoutBtn.href = '#';
    logoutBtn.className = 'cyber-link';
    logoutBtn.textContent = '退出';
    logoutBtn.onclick = handleLogout;
    navLinks.appendChild(logoutBtn);
}

// 更新UI为未登录状态
function updateUIForLoggedOut() {
    loginBtn.textContent = '登录';
    loginBtn.href = '#';
    const logoutBtn = document.querySelector('.cyber-link:last-child');
    if (logoutBtn && logoutBtn.textContent === '退出') {
        logoutBtn.remove();
    }
}

// 处理退出登录
function handleLogout(e) {
    e.preventDefault();
    localStorage.removeItem('token');
    window.location.reload();
}

// 切换登录/注册表单
tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const tab = btn.dataset.tab;
        
        // 更新按钮状态
        tabBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        
        // 显示对应表单
        if (tab === 'login') {
            loginForm.style.display = 'flex';
            registerForm.style.display = 'none';
        } else {
            loginForm.style.display = 'none';
            registerForm.style.display = 'flex';
            refreshCaptcha();
        }
    });
});

// 刷新验证码
function refreshCaptcha() {
    captchaImage.src = `/api/captcha?t=${new Date().getTime()}`;
}

// 处理登录表单提交
loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const email = document.getElementById('loginEmail').value;
    const password = document.getElementById('loginPassword').value;
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            token = data.token;
            localStorage.setItem('token', token);
            loginModal.style.display = 'none';
            window.location.reload();
        } else {
            showError(loginForm, data.error);
        }
    } catch (error) {
        console.error('登录失败:', error);
        showError(loginForm, '登录失败，请稍后重试');
    }
});

// 注册表单提交处理
registerForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('nickname', document.getElementById('nickname').value);
    formData.append('phone', document.getElementById('phone').value);
    formData.append('email', document.getElementById('registerEmail').value);
    formData.append('password', document.getElementById('registerPassword').value);
    formData.append('avatar', document.getElementById('avatar').files[0]);
    formData.append('captcha', document.getElementById('captcha').value);
    
    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('注册成功！', 'success');
            setTimeout(() => {
                showLoginForm();
                registerForm.reset();
                avatarPreview.src = '/images/default-avatar.png';
            }, 1500);
        } else {
            showMessage(data.error || '注册失败', 'error');
            refreshCaptcha();
        }
    } catch (error) {
        console.error('注册失败:', error);
        showMessage('注册失败，请稍后重试', 'error');
        refreshCaptcha();
    }
});

// 显示错误信息
function showError(form, message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    
    const existingError = form.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }
    
    form.appendChild(errorDiv);
}

// 显示成功信息
function showSuccess(form, message) {
    const successDiv = document.createElement('div');
    successDiv.className = 'success-message';
    successDiv.textContent = message;
    
    const existingSuccess = form.querySelector('.success-message');
    if (existingSuccess) {
        existingSuccess.remove();
    }
    
    form.appendChild(successDiv);
}

// 登录模态框控制
loginBtn.addEventListener('click', (e) => {
    if (loginBtn.textContent === '登录') {
        e.preventDefault();
        loginModal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
});

closeBtn.addEventListener('click', () => {
    loginModal.style.display = 'none';
    document.body.style.overflow = 'auto';
    loginForm.reset();
    registerForm.reset();
});

window.addEventListener('click', (e) => {
    if (e.target === loginModal) {
        loginModal.style.display = 'none';
        document.body.style.overflow = 'auto';
        loginForm.reset();
        registerForm.reset();
    }
});

// 验证码点击刷新
captchaImage.addEventListener('click', refreshCaptcha);

// 创建视频卡片
function createVideoCard(video) {
    const card = document.createElement('div');
    card.className = 'video-card';
    card.innerHTML = `
        <div class="video-thumbnail">
            <img src="${video.thumbnail}" alt="${video.title}">
            <div class="video-overlay">
                <i class="fas fa-play"></i>
            </div>
        </div>
        <div class="video-info">
            <h3>${video.title}</h3>
            <span class="views">${video.views} 次观看</span>
        </div>
    `;
    return card;
}

// 加载视频列表
function loadVideos() {
    videoGrid.innerHTML = '';
    mockVideos.forEach(video => {
        videoGrid.appendChild(createVideoCard(video));
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadVideos();
    checkLoginStatus();
    
    // 添加滚动动画效果
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
            }
        });
    });

    document.querySelectorAll('.video-card').forEach(card => {
        observer.observe(card);
    });
});

// 添加视频卡片样式
const style = document.createElement('style');
style.textContent = `
    .video-card {
        background: var(--card-background);
        border-radius: 10px;
        overflow: hidden;
        transition: transform 0.3s ease;
        opacity: 0;
        transform: translateY(20px);
    }

    .video-card.fade-in {
        opacity: 1;
        transform: translateY(0);
    }

    .video-card:hover {
        transform: translateY(-5px);
    }

    .video-thumbnail {
        position: relative;
        width: 100%;
        padding-top: 56.25%;
        overflow: hidden;
    }

    .video-thumbnail img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .video-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .video-overlay i {
        color: white;
        font-size: 2rem;
    }

    .video-card:hover .video-overlay {
        opacity: 1;
    }

    .video-info {
        padding: 1rem;
    }

    .video-info h3 {
        margin-bottom: 0.5rem;
        color: var(--text-color);
    }

    .views {
        color: var(--text-color);
        opacity: 0.7;
        font-size: 0.9rem;
    }
`;
document.head.appendChild(style); 